package com.wz.leetcode.string;

import com.sun.scenario.effect.impl.sw.java.JSWBlend_SRC_OUTPeer;

public class Atoi_8 {
    public static int myAtoi(String s) {
        int len = s.length();
        char[] charArray = s.toCharArray();

        // 1.去除开始的空格
        int index = 0;
        while (index < len && charArray[index] == ' ') {
            index++;
        }
        // 全是空格的情况
        if (index == len) {
            return 0;
        }

        // 符号位
        int sign = 1;
        if (charArray[index] == '+') {
            index++;
        } else if (charArray[index] == '-') {
            index++;
            sign = -1;
        }

        int res = 0;
        int MAX_HIGH = Integer.MAX_VALUE / 10;
        int MAX_LOW = Integer.MAX_VALUE % 10;
        int MIN_HIGH = Integer.MIN_VALUE / 10;
        int MIN_LOW = Integer.MIN_VALUE % 10;
        while (index < len) {
            char curr = charArray[index];
            if (curr < '0' || curr > '9') {
                break;
            }
            if (res > MAX_HIGH ||
                    (res == MAX_HIGH  && (curr - '0') > MAX_LOW)) {
                return Integer.MAX_VALUE;
            }
            if (res < MIN_HIGH ||
                    (res == MIN_HIGH  && (curr - '0') > -MIN_LOW)) {
                return Integer.MIN_VALUE;
            }

            res = res * 10 + sign * (curr - '0');
            index++;
        }
        return res;
    }

    public static void main(String[] args) {
        String str = "2147483646";
        int res = myAtoi(str);
        System.out.println("result:" + str + " to " + res);
        System.out.println("=======================");
        str = "2147483648";
        res = myAtoi(str);
        System.out.println("result:" + str + " to " + res);
        System.out.println("=======================");
        str = "-2147483647";
        res = myAtoi(str);
        System.out.println("result:" + str + " to " + res);
        System.out.println("=======================");
        str = "-2147483649";
        res = myAtoi(str);
        System.out.println("result:" + str + " to " + res);
        System.out.println("=======================");
        str = "  18";
        res = myAtoi(str);
        System.out.println("result:" + str + " to " + res);
        System.out.println("=======================");
        str = "  -18";
        res = myAtoi(str);
        System.out.println("result:" + str + " to " + res);
        System.out.println("=======================");
        str = "  h18";
        res = myAtoi(str);
        System.out.println("result:" + str + " to " + res);
        System.out.println("=======================");

        System.out.println(Integer.MIN_VALUE % 10);
        System.out.println(-8 % 10);

        System.out.println(Integer.MAX_VALUE);
        System.out.println(Integer.MIN_VALUE);
    }
}
